import axios from 'axios'
// import router from '@/router'
import store from '@/vuex/store'
import { getToken } from '@/utils/TokenUtil'
import { message, notification, Modal } from 'ant-design-vue'

// 请求配置
const BASE_URL = process.env.VUE_APP_BASE_API_URL  // 服务端地址
const SOURCE = process.env.VUE_APP_SOURCE // 来源渠道

// 创建
const request = axios.create({
    baseURL: BASE_URL,
    timeout: 60000
})

// 响应拦截器
request.interceptors.response.use(
    // http状态为200处理
    response => {
        let code = response.data.code
        let status = response.status
        codeHandle(code ? code : status, response)
        return response
    },
    // http状态非200处理
    error => {
        let response = error.response
        // 处理状态码弹出特殊提示
        if (response) {
            let status = response.status
            codeHandle(status, response)
            return Promise.reject(error)
        }
    }
)
function codeHandle(code, response) {
    switch (code) {
        case 200:
            break;
        case 401:
            Modal.error({
                title: '登录已过期',
                content: '很抱歉，登录已过期，请重新登录',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                    store.dispatch('LOGOUT') // 登出
                }
            })
            // notification.error({ message: "系统提示", description: response.data.msg })
            break;
        case 888:
            Modal.error({
                title: '登录已过期',
                content: '账号在异地登录，您已被登出，如非本人操作，请立即修改密码！',
                okText: '重新登录',
                mask: false,
                onOk: () => {
                    store.dispatch('LOGOUT') // 登出
                }
            })
            break;
        case 400:
            message.error({ content: response.data.msg, duration: 2 })
            break;
        case 504:
            notification.error({ message: "系统提示", description: '网络超时' })
            break;
        case 403:
            notification.error({ message: "系统提示", description: '权限不足,请联系超级管理员开通' })
            break;
        case 404:
            notification.error({ message: "系统提示", description: '很抱歉，资源未找到' })
            break;
        case 500:
            if (response.data) {
                message.error({ content: response.data.msg, duration: 2 })
            } else {
                notification.error({ message: "系统提示", description: '服务器繁忙,请稍后重试!' })
            }
            break;
        case 777:
            notification.error({ message: "系统提示", description: '导出参数有误,请检查!' })
            break;
        default:
            notification.error({ message: "系统提示", description: '服务器繁忙,请稍后重试!' })
            break;
    }
}
// 请求拦截器
request.interceptors.request.use(res => {
    res.headers['source'] = SOURCE
    const token = getToken()
    if (token) {
        res.headers['Authorization'] = token
    }
    return res;
}, function (error) {
    return Promise.reject(error);
});

export default request
